<script lang="ts" setup>
import type { FormInstance } from 'ant-design-vue';
import { $t } from '@vben/locales';
import type { UserGroup } from './types';
import { onMounted,onUpdated, onActivated, onUnmounted, reactive, ref, watch, computed } from 'vue';
import { message } from 'ant-design-vue';
import { removeEmpty, transformPermissionsTreeData } from '#/utils/common';
import { useDebounceFn } from '@vueuse/core';
import { getUserGroupAll } from '../user_group/homeapi';
import { getUserPermissions, getGroupPermissions, getAllPermissions, getCheckedGroupPermissions } from '../permissions/homeapi';
import type { Permissions } from '../permissions/types.js';
import type { tPermissions } from '../permissions/hometypes.js';
import type { GroupHasPermission } from '../group_has_permission/types';
import { connectChecked } from '../group_has_permission/homeapi';

const loading = ref(false);
const editStatusStart = ref('');
const editStatusEnd = ref('');  //控制控件关闭时不再调用接口
const props = defineProps<{
  mode: 'add' | 'edit' | 'permission';
  record: UserGroup | null;
  visible: boolean;
}>();

const emit = defineEmits(['update:visible', 'success']);

const formRef = ref<FormInstance>();
const formState = reactive<Partial<GroupHasPermission>>({
group_id:'',
status:1,
permission_name:'',
group_name:'',
code:''
});
 

/** rules */
const rules = {
  group_id: [{ message: '不能为空', required: true }],
  permission_name: [{ message: '不能为空', required: false }],
  status: [{ message: '不能为空', required: true }],
  group_name: [{ message: '不能为空', required: true }],
  code: [{ message: '不能为空', required: true }]
};


watch(
  () => props.record,
  (newVal) => {
    console.log(props.record);
    formState.permission_name = "";
    formState.group_id = props.record?.id;
    formState.status = props.record?.status ? props.record?.status : 1;
    formState.group_name = props.record?.group_name;
    formState.code = props.record?.code;
  },
  { immediate: true },
);

const handleOk = () => {
  console.log(formState);
    interface Formated {
      id?:string,
      permission_name?: string,
      group_id?: string,
      status?: number,
      group_name: string,
      code: string,
      checkedPermissionIds: Permissions[]
     };

    const formatedFormState: Formated = {
      id: formState.id,
      permission_name: formState.permission_name,
      group_id: formState.group_id,
      status: Number(formState.status),
      group_name: formState.group_name,
      code: formState.code,
      checkedPermissionIds: checkedKeys.value
     };

  formRef.value?.validate().then(async () => {
    try {
        await connectChecked(removeEmpty(formatedFormState));
        message.success('编辑成功');
      emit('success');
    } catch {
      message.error('操作失败');
    }
  }); 
};

const handleCancel = () => {
  emit('update:visible', false);
};

const groupOptions = ref<any[]>([]);

const rawSearch = async (searchText: string) => {
  if (!searchText) {
    groupOptions.value = [];
    return;
  }

  loading.value = true;
  try {
   /* const res = await getUserGroupList(0, 50, { group_name: searchText });
    console.log('搜索结果:', res);

    const validDatas = res.userGroups.filter(
      (item) => item.deleted_at === null,
    );
    groupOptions.value = validDatas.map((item) => ({
      label: item.group_name,
      value: item.id,
    })); */
  } catch (error) {
    console.error('搜索错误:', error);
    message.error('获取用户列表失败');
    groupOptions.value = [];
  } finally {
    loading.value = false;
  }
};

const onSearch = useDebounceFn(rawSearch, 500);
const transformedTreeData = ref<tPermissions[]>();

const fetchData = async () => {
  loading.value = true;
 
  try {
    const resUserGroupAll = await getUserGroupAll();
    console.log(resUserGroupAll);
    groupOptions.value = resUserGroupAll.map((item) => ({
      label: item.group_name,
      value: item.id,
    }));
    
  } catch {
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

const refreshData = async () => {
  editStatusStart.value = props.mode;
  loading.value = true;
  try {
    const postData = {id: props.record?.id};
    const resAllPermissions = await getAllPermissions(postData);
    checkedKeys.value = selectedKeys.value = await getCheckedGroupPermissions(postData);
   // console.log(resGroupPermissions);
   // transformedTreeData.value = resUserPermissions.permissionss;
    transformedTreeData.value = transformPermissionsTreeData(resAllPermissions);
    console.log(transformedTreeData.value);
  } catch {
    message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

const selectedKeys = ref<Permissions[]>([]);
const checkedKeys = ref<Permissions[]>([]);
watch(selectedKeys, () => {
  console.log('selectedKeys', selectedKeys);
});
watch(checkedKeys, () => {
  console.log('checkedKeys', checkedKeys);
});

onMounted(() => {
  fetchData();
});

onUpdated(() => {
  console.error('onUpdated:');
  refreshData()
});

onUnmounted(() => {
  console.error('onUnmounted:');
});
</script>

<template>
  <a-modal
    :open="visible"
    :title="mode === 'add' ? '新增' : '编辑'"
    @cancel="handleCancel"
    @ok="handleOk"
  >

  <a-form ref="formRef" :model="formState" :rules="rules">
    <a-form-item :label="$t('database_column.user_has_group.group_id')" name="group_id">
        <a-input v-model:value="formState.group_id"/>
    </a-form-item>
    <a-form-item :label="$t('database_column.user_group.group_name')" name="group_name">
          <a-input v-model:value="formState.group_name" />
    </a-form-item>
    <a-form-item :label="$t('database_column.user_group.code')" name="code">
          <a-input v-model:value="formState.code" />
    </a-form-item>
    <a-form-item :label="$t('database.permissions')" name="group_permissions">
        <a-tree v-model:selectedKeys="selectedKeys" v-model:checkedKeys="checkedKeys" checkable  :tree-data="transformedTreeData" />
    </a-form-item>
  </a-form>

  </a-modal>
</template>
